const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

router.use(authenticateToken);

// 获取快捷项列表
router.get('/', async (req, res) => {
    try {
        const { book_id } = req.query;
        const userId = req.user.user_id;

        let query = 'SELECT * FROM quick_items WHERE user_id = ?';
        const params = [userId];

        if (book_id) {
            query += ' AND (book_id = ? OR book_id IS NULL)';
            params.push(book_id);
        } else {
            query += ' AND book_id IS NULL';
        }

        query += ' ORDER BY use_count DESC, sort_order ASC';

        const [items] = await db.query(query, params);

        res.json({ code: 200, data: items });
    } catch (error) {
        console.error('获取快捷项失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 创建快捷项
router.post('/', async (req, res) => {
    try {
        const { book_id, item_name, type, amount, category, icon } = req.body;
        const userId = req.user.user_id;

        const [result] = await db.query(
            `INSERT INTO quick_items (user_id, book_id, item_name, type, amount, category, icon)
             VALUES (?, ?, ?, ?, ?, ?, ?)`,
            [userId, book_id || null, item_name, type, amount, category, icon || '💰']
        );

        res.json({
            code: 200,
            message: '快捷项创建成功',
            data: { item_id: result.insertId }
        });
    } catch (error) {
        console.error('创建快捷项失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 使用快捷项记账
router.post('/:id/use', async (req, res) => {
    try {
        const { id } = req.params;
        const { book_id, remark, date } = req.body;
        const userId = req.user.user_id;

        // 获取快捷项信息
        const [[item]] = await db.query(
            'SELECT * FROM quick_items WHERE item_id = ? AND user_id = ?',
            [id, userId]
        );

        if (!item) {
            return res.status(404).json({ code: 404, message: '快捷项不存在' });
        }

        // 添加记录
        await db.query(
            `INSERT INTO records (user_id, book_id, type, amount, category, date, remark)
             VALUES (?, ?, ?, ?, ?, ?, ?)`,
            [userId, book_id || item.book_id, item.type, item.amount, item.category, date || new Date().toISOString().split('T')[0], remark || item.item_name]
        );

        // 更新使用次数
        await db.query(
            'UPDATE quick_items SET use_count = use_count + 1, last_used_at = NOW() WHERE item_id = ?',
            [id]
        );

        res.json({ code: 200, message: '记账成功' });
    } catch (error) {
        console.error('使用快捷项失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 更新快捷项
router.put('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { item_name, amount, icon } = req.body;
        const userId = req.user.user_id;

        await db.query(
            `UPDATE quick_items 
             SET item_name = COALESCE(?, item_name),
                 amount = COALESCE(?, amount),
                 icon = COALESCE(?, icon)
             WHERE item_id = ? AND user_id = ?`,
            [item_name, amount, icon, id, userId]
        );

        res.json({ code: 200, message: '快捷项更新成功' });
    } catch (error) {
        console.error('更新快捷项失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 删除快捷项
router.delete('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.user_id;

        await db.query('DELETE FROM quick_items WHERE item_id = ? AND user_id = ?', [id, userId]);

        res.json({ code: 200, message: '快捷项删除成功' });
    } catch (error) {
        console.error('删除快捷项失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

module.exports = router; 